"use strict";

/**
 * 限制过快访问
 */

var Router = require('koa-router');
var appUtil = require('../common/app_utils.js');

var __pathPrefix = '/'; // 所有请求都需要 ip访问频率限制
appUtil.appLog('router:' + __pathPrefix);
var router = new Router({
  prefix: __pathPrefix
});

// redis load lua
var redis = require('../conn/redis.js').redis;
var redisCli = require('../conn/redis.js').client;
//redis.lua('myset','return redis.call("incr",KEYS[1])');
var fs = require('fs');
let path = require('path');
var freqCheck = fs.readFileSync(path.join(__dirname, '../lua/check_ip_freq.lua'), 'utf8');
redis.lua('freqCheck', freqCheck);

//
router.all('**', function*(next) {
  console.log('router ipfreqCheck');
  //__ipFreqCheck.call(this);
  var res = yield __ipFreqCheck2(this);
  if (res.error) {
    return this.body = 'system error';
  } else if (res.res <= 0) {
    this.status = 429;
    return this.body = 'Too Many Requests 访问太频繁'
  }
  yield next;
});

/**
 * 检测访问频率
 * @private
 */
function __ipFreqCheck() {
  var req = this.req;
  var fromIp = req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
  //redisCli.myset(1, fromIp); // ok

  redisCli.freqCheck(1, fromIp, function (err, res) { // this works
    console.log('aaaa');
    if (err) console.log('err ', err);
    if (res) console.log('res ', res);
    //console.log(err || res);
  });
}

/**
 * 检测访问频率
 * @private
 */
function * __ipFreqCheck2(app) {
  var req = app.req;
  var fromIp = req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
  return new Promise(function (fulfil, reject) {
    redisCli.freqCheck(1, fromIp, function (err, res) { // this works
      console.log('aaaa');
      fulfil({error: err, res: res});
      console.log(err || res);
    });
  });
}


module.exports = router.routes();